<?php
/**
 * @orm tablename clients
 */
class Client extends DomUser {
	/**
	 * @orm char(20)
	 */
	public $clientId;
	/**
	 * @orm char(20)
	 */
	public $electricitySupplier;
	const T2ES1 = 'T2ES1';
	const T2ES2 = 'T2ES2';
	/**
	 * @orm has children MeterReading inverse client
	 */
	public $meterReadings;
	/**
	 * @orm has children Task inverse client
	 */
	public $tasks;
	/**
	 * @orm has parent AdminUser inverse clients
	 */
	public $admin;
	
	public function addTask() {
		
		if ( $this->checkOpenTask() == 1001 ) {
			return;
		}
		
		$task = new Task();
		$task->client = $this;
		$task->admin = $this->admin;
		$task->save();
		
	}
	
	public function checkOpenTask() {

		if ( $this->tasks ) {
			foreach ( $this->tasks as $task ) {
				if ( $task->done == false ) {
					return 1001;
				}
			}
		}
		
		return 0;
	}
	
	public function getLatesMeterReading() {
		$result = $this->meterReadings->dataQuery()->select('t.reading')->orderBy('t.datetime DESC')->limit(1)->commit();
		return (float)$result['reading'];		
	}
	
	public static function getClient( $clientPrefix, $areaId, $facilityId) {
		$client = Client::query()
			->where('t.clientPrefix = \''.$clientPrefix.'\' 
					AND t.areaId = '.(int)$areaId.'
					AND t.facilityId = '.(int)$facilityId.' ')
			->limit(1)
			->commit();
			
		return $client;			
	}
	
	
	public function getClientMeterReadings() {
		return MeterReading::query()->where('t.client = '.(int)$this->id)->orderBy('t.datetime DESC')->commit()->toArray();
	}
}
?>